import BackPage from '@/components/BackPage';
import SelectOne from '@/components/SelectOne';
import { getAllWrite, removeWrite } from '@/services/write';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

const Notice: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [selectList, setSelectList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      await getAllWrite({ pageIndex: currentPage }).then((res) => {
        setTotal(res.total);
        setList(res.list);
      });
    } catch (error) {
      console.log(error);
    }
  }, [currentPage]);

  useEffect(() => {
    getList();
  }, [getList]);

  const delectOne = (id: string) => {
    Modal.confirm({
      title: '',
      content: '您确定删除该资讯吗？',
      okText: '删除',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        try {
          await removeWrite({ id: id }).then(() => {
            message.success('删除成功！');
            getList();
          });
        } catch (error) {
          console.log(error);
        }
      },
    });
  };

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '资讯编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '资讯标题',
      dataIndex: 'title',
      ellipsis: true,
      render: (text, record) => {
        return (
          <div
            key={record.id}
            onClick={() => {
              history.push({
                pathname: './write',
                query: { lastRoute: '养生小专栏', id: record.id },
              });
            }}
            className={styles.ellipsis}
            style={{ cursor: 'pointer' }}
          >
            {record.title}
          </div>
        );
      },
    },
    {
      title: '作者',
      dataIndex: 'author',
      ellipsis: true,
      render: (text, record) => {
        return <div key={record.id}>四季养生购物网站</div>;
      },
    },
    {
      title: '发布时间',
      key: 'date',
      dataIndex: 'date',
      valueType: 'date',
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeadd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div key={record.id} className={styles.btns}>
          <div
            className={styles.delete}
            onClick={() => {
              history.push({ pathname: '/addAdvice', query: { id: record.id } });
            }}
            style={{ border: `1px solid ${colorThem}`, color: colorThem, marginRight: 35 }}
          >
            编辑
          </div>
          <div
            className={styles.delete}
            onClick={() => {
              delectOne(record.id);
            }}
            style={{ border: `1px solid ${colorThem}`, color: colorThem }}
          >
            删除
          </div>
        </div>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/notice'} lastRoute={'资讯管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'资讯标题'}
          fromWhere={'notice'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
      </div>
    </BackPage>
  );
};
export default Notice;
